package com.zhiyou100.login;

import com.zhiyou100.dao.TeacherDao;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.TreeSet;

/**
 * @packageName: ${NAME}
 * @className: ${PACKAGE_NAME}
 * @Description: TODO 判断是否登陆成功
 * @author: yang
 * @date: 7/20/20
 */
@WebServlet(name = "Login", urlPatterns = "/login")

public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 设定编码集
        response.setContentType("text/html;charset=UTF-8");
        // 设定类型


        // 获取参数
        String tname = request.getParameter("tid");
        String tpwd = request.getParameter("tpwd");

        // 创建 TeacherDao
        TeacherDao teacherDao = new TeacherDao();
        // 判断是否登陆成功！
        boolean b = teacherDao.flagOfLogin(tname, tpwd);
        if (b) {
            // 登陆成功
            // 获取 application 对象
            ServletContext servletContext = request.getServletContext();
            // 获取 登陆人数属性
            Object loginNumber = servletContext.getAttribute("loginNumber");
            if (loginNumber == null) {
                // 登陆人数是 null，说明是第一个登陆者
                TreeSet<String> usersName = new TreeSet<>();
                usersName.add(tname);
                servletContext.setAttribute("loginNumber", usersName);
            } else {
                // 不是第一个，添加到集合
                ((TreeSet<String>) loginNumber).add(tname);
                servletContext.setAttribute("loginNumber", loginNumber);
            }
            // 设置 Session 保存登陆信息， user 为 true
            request.getSession().setAttribute("user", true);
            // 把 用户名放入 Session 中
            request.getSession().setAttribute("userName", tname);
            // 请求转发到 主页
            request.getRequestDispatcher("/jsp/home.jsp").forward(request, response);
        } else {
            // 登陆不成功， user 为 false
            request.getSession().setAttribute("user", false);
            // 转发到登陆的 login.jsp
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);

        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

}
